// 关于侧边菜单的相关数据以及操作
import { defineStore } from "pinia";
import type { RouteRecordRaw ,RouteLocationNormalized} from "vue-router";
import { baseRoutes } from "/@/router/modules/routes";
import type { menuList, menu } from "./types";

export const useMenuStore = defineStore({
  id: "menu", // id必填，且需要唯一
  state: (): menuList => {
    const menuList: menu[] = [];

    return { menuList: menuList, baseRouter: baseRoutes ,};
  },
  actions: {
    // 生成菜单
    menuRecursion(arr: RouteRecordRaw[]) {
      const onEcursion = (list: RouteRecordRaw[]): menu[] => {
        return list.reduce((pre: any, cur: RouteRecordRaw) => {
          
          if (cur.meta?.isMenu) {
            return pre.concat([
              {
                name: cur.name,
                icon:cur.meta.icon,
                path: cur.path,
                title: cur.meta.title,
                children: cur.children
                  ? onEcursion(cur.children)
                  : [],
              },
            ]);
          } else {
            return pre.concat([]);
          }
        }, []);
      };
      this.menuList = onEcursion(arr);
    },
    updateMenu(name: string, key?: string, value?: string) {
      const onEcursion = (list: any[]) => {
        return list.reduce((pre: any, cur: any) => {
          if (cur.name === name && key) {
            cur[key] = value;
            return pre.concat([cur]);
          } else if (cur.name === name && !key) {
            return pre.concat([]);
          } else {
            return pre.concat([cur]);
          }
        }, []);
      };
      this.menuList = onEcursion(this.menuList);
    },
  },
});
